﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Antu.WebControls;
using Antu.Core.Components;
using Antu.Core.Services;
using System.Web.UI.WebControls;
using System.Web;
using Antu.WorkFlowFactory;
using System.Data;
using System.Configuration;

namespace WebSys.UI.OfficeFlow
{
    public class TransactbusinessSkin : MPBasicTemplate
    {
        FlowFactoryProvider _FlowFactoryProvider = (FlowFactoryProvider)ProviderService.ProviderServiceMange.GetProvider("FlowFactoryProvider");
        TextBox taskname, txtbh, txtxmname, txtzsh, txtzl, txtzsr;
        CustomGridView CustomGridView1;
        DropDownList ddlqh,ddltype;
        string query = "";
        Button search;
        
        protected string UserId
        {
            get { if (base.Page.Session["UserId"] != null) { return base.Page.Session["UserId"].ToString(); } else { return string.Empty; } }
            set { base.Page.Session["UserId"] = value; }
        }
        protected override void OnLoad(EventArgs e)
        {
            LoginHelper.CheckLogin();
            InitControl();
            base.OnLoad(e);
            if (!base.Page.IsPostBack) {
                if (base.Page.Request.QueryString.Count > 0)
                {
                    string action = base.Page.Request["action"].ToString();
                    if (action == "qxsq")
                    {
                        string iid = base.Page.Request["iid"].ToString();
                        if (!string.IsNullOrEmpty(iid))
                        {
                            if (_FlowFactoryProvider.NewCancelApplySuspend(iid, UserId))
                            {
                                base.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('取消申请成功')</script>");
                            }
                        }
                    }
                }
                GetQuHua();
                BindDDL();
                Initcy();
                
            }
        }
        private void InitControl()
        {
            //txtbh, txtxmname, txtzsh, txtzl, txtzsr
            txtbh = (TextBox)FindControl("txtbh");
            txtxmname = (TextBox)FindControl("txtxmname");
            txtzsh = (TextBox)FindControl("txtzsh");
            txtzl = (TextBox)FindControl("txtzl");
            txtzsr = (TextBox)FindControl("txtzsr");
            taskname = (TextBox)FindControl("taskname");
            ddlqh = (DropDownList)FindControl("ddlqh");
            ddltype = (DropDownList)FindControl("ddltype");
            search = (Button)FindControl("search");
            search.Click += new EventHandler(search_Click);
            CustomGridView1 = (CustomGridView)FindControl("CustomGridView1");
            CustomGridView1.OnLoadData += new EventHandler(CustomGridView1_OnLoadData);
            query = " and 案件类型 in(" + ConfigurationManager.AppSettings["ZSAnJianType"].ToString()+")";
            if (!string.IsNullOrEmpty(taskname.Text))
            {
                query += " and 申请单位 like '%" + taskname.Text + "%' ";
            }
            if (txtbh.Text.Trim() != "")
            {
                query += " and 顺序号 like '%" +_FlowFactoryProvider.GetCaseIdLike(txtbh.Text.Trim()) + "%'";
            }
            if (ddltype.SelectedValue != "全部" && ddltype.SelectedValue!="")
            {
                query += " and 案件类型='" + ddltype.SelectedValue + "'";//房屋征收补偿决定
            }
        }

        public void search_Click(object sender, EventArgs e)
        {
            Initcy();
        }
        //绑定行政区划下拉框
        public void GetQuHua()
        {
            string sql = @"select keyname from zs_params where name = '区属'";
            DataTable dt = _FlowFactoryProvider.GetOneDs("(" + sql + ")", "*", "").Tables[0];
            ddlqh.DataValueField = "keyname";
            ddlqh.DataTextField = "keyname";
            ddlqh.DataSource = dt;
            ddlqh.DataBind();
            ddlqh.Items.Insert(0, "所有");

        }

        /// <summary>
        /// 查询方法
        /// 因为查询条件不同，所以所用到的Sql语句也不同
        /// </summary>
        private void Initcy()
        {
           // //txtbh, txtxmname, txtzsh, txtzl, txtzsr
            CustomGridView1.RowDataBound += new GridViewRowEventHandler(CustomGridView1_RowDataBound);
            DataTable dt =new DataTable ();
            string where = "";
            string xmnamewhere = "";
            string zshwhere = "";
            string zlwhere = "";
            string zsrwhere = "";
            string qswhere = "";
            string bhwhere = "";
            string dwwhere = "";
            string typewhere = "";
            string adminid = System.Configuration.ConfigurationManager.AppSettings["OfficeSearch"].ToString();
            string[] aids = adminid.Split(',');
            string sql = "";
            bool flag = false;
            foreach (string item in aids)
            {
                if (UserId == item)
                {
                    flag = true;
                }
            }
            if (flag)
            {
                sql = "select * from sv_getinstancelist where 1=1 and 案件类型 in(" + ConfigurationManager.AppSettings["ZSAnJianType"].ToString() + ")";
            }
            else
            {
                sql = @"select * from sv_getinstancelist t where 1=1  and 案件类型 in(" + ConfigurationManager.AppSettings["ZSAnJianType"].ToString() + ")" + "and (userid = '" + UserId + "' or userid in (select userid from st_delegate Where delegate_userid = '" + UserId + "' And (delegate_task = t.案件类型 or delegate_task = '全部') and begin_time <= Sysdate And end_time >= Sysdate)) ";           
            }
            if (_FlowFactoryProvider.IsCJAdmin(UserId)) {
                sql = "select * from sv_getinstancelist where 1=1 and 案件类型 in(" + ConfigurationManager.AppSettings["ZSAnJianType"].ToString() + ")";
            }
            if (txtxmname.Text.Trim() != "" || txtzsh.Text.Trim() != "" || txtzl.Text.Trim() != "" || txtzsr.Text.Trim() != "" || ddlqh.SelectedValue!="所有")
            {

                if (txtxmname.Text.Trim()!="")
                {
                    xmnamewhere = " and 项目名称 like '%"+txtxmname.Text.Trim()+"%'";
                }
                if (txtzsh.Text.Trim()!="")
                {
                    zshwhere = " and 征收许可证号 like '%" + txtzsh.Text.Trim() + "%' or 征收许可证号 like'%" + ReturnString2(txtzsh.Text.Trim()) + "%'";
                }
                if (txtzl.Text.Trim()!="")
                {
                    zlwhere = " and 房屋坐落 like '%"+txtzl.Text.Trim()+"%'";
                }
                if (txtzsr.Text.Trim()!="")
                {
                    zsrwhere = " and 产权人 like '%"+txtzsr.Text.Trim()+"%'";
                }
                if (ddlqh.SelectedItem.Text!="所有")
                {
                    qswhere = " and 区属 like '%"+ddlqh.SelectedValue+"%'";
                }
                if (txtbh.Text.Trim() != "")
                {
                    //bhwhere = @" and ((i.iid in (select iid from zs_case_register where CASEID like '%" + ReturnString(txtbh.Text.Trim()) + @"%')) or 
                    //(i.iid like '%" + txtbh.Text.Trim() + "%'))";
                    bhwhere= " and 顺序号 like '%" + txtbh.Text.Trim() + "%' or 顺序号 like '%"+ReturnString(txtbh.Text.Trim())+"%'";
                }
                if (!string.IsNullOrEmpty(taskname.Text))
                {
                    dwwhere = " and 申请单位 like '%" + taskname.Text + "%' ";
                }
                if (ddltype.SelectedValue!="全部" && ddltype.SelectedValue!="")
                {
                    typewhere = " and 案件类型='"+ddltype.SelectedValue+"'";//房屋征收补偿决定
                }
                where = string.Format( @" and t.siid in (
    select iid from xt_instance_ext where 关联ID in (
           select id from zs_zzbcjfenhu where 1=1 
           and ZSPID in (
               select id from zs_zsperson where 1=1 
              {0} {1} )
           and pid in (
           select id from zs_prono where 1=1 
           {2}
           and pid in (
               select id from zs_project where 1=1 
               {3}
               {4}
               )))) {5} {6} {7}",zlwhere,zsrwhere,zshwhere,qswhere,xmnamewhere,bhwhere,dwwhere,typewhere);
                
                sql += where + "  order by  接收时间 desc";
                dt = _FlowFactoryProvider.DoDataTableSql(sql);
            }
            else
            {
                dt = _FlowFactoryProvider.GetInstanceListByUserId(UserId, query);
            }
                      
            CustomGridView1.DataSource = dt;
            CustomGridView1.RecordCount = dt.Rows.Count;
            CustomGridView1.DataBind();
        }

        public string ReturnString(string txt)
        {
            string str = string.Empty;
            if (txt.Trim().Length == 8)
            {
                int i;
                if (int.TryParse(txt.Trim(), out i))
                {
                    string nian = txt.Trim().Substring(0, 4);
                    string yue = txt.Trim().Substring(4, 4);
                    str = nian + "）第" + yue;
                }
                else
                {
                    str = txt;
                }
            }
            else
            {
                str = txt;
            }
            return str;

        }

        public string ReturnString2(string txt)
        {
            string str = string.Empty;
            if (txt.Trim().Length == 7)
            {
                int i;
                if (int.TryParse(txt.Trim(), out i))
                {
                    string nian = txt.Trim().Substring(0, 4);
                    string yue = txt.Trim().Substring(4, 3);
                    str = nian + "年第" + yue;
                }
                else
                {
                    str = txt;
                }
            }
            else
            {
                str = txt;
            }
            return str;
        }

        protected void CustomGridView1_OnLoadData(object sender, EventArgs e)
        {
            Initcy();
        }
        protected void CustomGridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow) {
                DataRowView rowview = (DataRowView)e.Row.DataItem;
                string strIId = rowview["顺序号"].ToString();//caseid--iid

                //限制顺序号的显示格式
                string sxh = strIId.Replace("征补字（", "");
                string s = sxh.Replace("）第", "");
                string x = s.Replace("号", "");
                e.Row.Cells[5].Text = x;
                string strsIId = rowview["siid"].ToString();//iid
               // int temp = Convert.ToInt32(_FlowFactoryProvider.GetOneStrString("xt_suspend_apply", "count(*)", "serial", strsIId));
                int tt = Convert.ToInt32(_FlowFactoryProvider.GetSomeStr("xt_suspend_apply", "count(*)", " and isdelete is null and ISCHECKUP='1' and serial='" + strsIId + "'"));
                int t = Convert.ToInt32(_FlowFactoryProvider.GetSomeStr("xt_suspend_apply", "count(*)", " and isdelete is null and ISCHECKUP is null and serial='" + strsIId + "'"));

                if (t > 0)
                {

                    e.Row.Cells[4].Text = "<a href='?action=qxsq&iid=" + strsIId + "' onclick='return confirm(\"你确定要取消吗\")'>取消申请</a>";
                    e.Row.Cells[3].Text = "<img src='../../Themes/Default/Images/Icons/handler.png' style='width:25px;border-width:0px;'  />";
                }
                if (tt > 0)
                {
                    e.Row.Cells[4].Text = "已挂起";
                    e.Row.Cells[3].Text = "<img src='../../Themes/Default/Images/Icons/handler.png' style='width:25px;border-width:0px;'  />";
                }
                Image img = e.Row.FindControl("img") as Image;
                string yxj = rowview["优先级"].ToString();
                if (yxj == "1")
                {
                    img.ImageUrl = "../../Themes/Default/Images/top_ico_yxj2.gif";
                }
                if (yxj == "2")
                {
                    img.ImageUrl = "../../Themes/Default/Images/top_ico_yxj3.gif";
                }
            }
        }

        private void BindDDL()
        {
            string s = System.Configuration.ConfigurationManager.AppSettings["CaiJueKe"].ToString();
            if (UserId != s)
            {
                string ajlx = ConfigurationManager.AppSettings["ZSAnJianType"].ToString();
                DataTable dt = _FlowFactoryProvider.NewGetStartWorkFlowListByUserId(UserId, ajlx); 
                ListItem item = new ListItem("全部");
                List<ListItem> itemlist = new List<ListItem>();
                itemlist.Add(item);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int temp = 0; temp < dt.Rows.Count; temp++)
                    {
                        item = new ListItem(dt.Rows[temp]["wname"].ToString());
                        itemlist.Add(item);
                    }
                    ddltype.DataSource = itemlist;
                    ddltype.DataBind();
                }
            }
            else
            {
                ddltype.Items.Insert(0, "房屋征收补偿决定");
            }
            
        }
    }
}


